﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using NBlog.Web.Application.Infrastructure;
using NBlog.Web.Application.Service;
using NBlog.Web.Application.Service.Entity;

namespace NBlog.Web.Controllers
{
    public partial class SearchController : LayoutController
    {
        public SearchController(IServices services) : base(services) { }

        [HttpGet]
        public ActionResult Index()
        {
            return View(new IndexModel {Results = new List<SearchResultModel>()});
        }

        [HttpPost]
        public ActionResult Index(string queryText)
        {
            if (string.IsNullOrEmpty(queryText))
                return RedirectToAction("Index");

            var entries = new List<BaseEntity>();
            Services.Page.GetList().ForEach(entries.Add);
            Services.Article.GetList().ForEach(entries.Add);
            Services.Review.GetList().ForEach(entries.Add);

            var results =
                entries
                    .Where(e => e.Title.IndexOf(queryText, StringComparison.OrdinalIgnoreCase) >= 0)
                    .Select(e => new SearchResultModel { Slug = e.Slug, Title = e.Title, Date = e.DateCreated.ToDateString()});

            Services.Search.AddSearch(queryText);

            var model = new IndexModel { Results = results, QueryText = queryText };
            return View(model);
        }
    }
}
